﻿using System;
using System.Linq;
using System.Linq.Expressions;
using SoftRemoval.Model;
using Xtensive.Orm;

namespace SoftRemoval
{
  public class SoftRemoveFilterApplier : QueryRootBuilder
  {
    private readonly QueryEndpoint originalQuery;

    protected override Expression BuildRootExpression<TEntity>()
    {
      // Build original query
      var query = originalQuery.All<TEntity>();

      if (!typeof (SoftRemovableEntity).IsAssignableFrom(typeof (TEntity)))
        // Entity does not support soft-removal.
        return query.Expression;

      return query.Where(GetFilter<TEntity>()).Expression;
    }

    private Expression<Func<TEntity, bool>> GetFilter<TEntity>()
    {
      var entity = Expression.Parameter(typeof (TEntity), "e");
      var body = Expression.Not(Expression.Property(entity, "IsHidden"));
      return (Expression<Func<TEntity, bool>>) Expression.Lambda(body, entity);
    }

    public SoftRemoveFilterApplier(QueryEndpoint originalQuery)
    {
      this.originalQuery = originalQuery;
    }
  }
}